package com.example.lostandfoundsystem.web.middleware;

import cn.hutool.core.util.URLUtil;
import com.example.lostandfoundsystem.models.system.Admin;
import com.example.lostandfoundsystem.services.common.ResultService;
import com.example.lostandfoundsystem.services.common.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author lucifer
 * @since 2024-07-26-17:36
 */
public class AuthAdminPermissionMiddleware implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //假定你已经是管理员了
        if (UserService.getThreadInstance().getAdmin() == null) {
            //如果获取用户是空，说明没有登陆，返回false拦截，并返回json
            return ResultService.middlewareGetUnauthAccessResultJSON(response);
        }
        //获得uri
        String path = URLUtil.getPath(request.getRequestURL().toString());
        //获得请求方式
        String method = request.getMethod();
        if (checkPermission(path, method)) {
            //如果没有权限则返回401
            return ResultService.middlewareGetUnauthAccessResultJSON(response);
        }
        //有权限就继续
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private boolean checkPermission(String path, String method) {
        //当前管理员
        Admin admin = UserService.getThreadInstance().getAdmin();
        return admin.checkPermission(method, path);
    }
}
